package com.krui.iweibo.ui;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.krui.iweibo.R;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

@SuppressLint({ "HandlerLeak", "SetJavaScriptEnabled" })
public class WebViewActivity extends BaseActivity {

	private WebView webView;
	/** 进度条对话框 */
	private ProgressDialog proDialog;
	
	public static String PIN = null;

	private static final int CLOSE_DLG = 1;
	
	private static final int LOADING_DLG = 2;

	private String url = null;

	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (msg.what == CLOSE_DLG) {
				//关闭进度条
				dismissDialog(LOADING_DLG);
			}

		};
	};

	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		this.setContentView(R.layout.webview);
		
		Intent i = getIntent();
		
		//url = OAuthUtils.getAuthorizationURL();
		
		url = i.getStringExtra("url");
		
		if (url == null) {
			showHintDialog(getString(R.string.auth_url_empty));
			return;
		}
		
		init();

		//这里是处理授权页面的load，
		load(url, webView);

	}

	public void init() {

		//显示进度条（context方法）
		showDialog(LOADING_DLG);

		webView = (WebView) this.findViewById(R.id.wv_oauth);

		webView.getSettings().setJavaScriptEnabled(true);
		
		webView.getSettings().setSupportZoom(true);
		webView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.MEDIUM);
		webView.getSettings().setBuiltInZoomControls(true);
		
		webView.addJavascriptInterface(new JavaScriptInterface(), "JSMethod");

		webView.setWebViewClient(new WebViewClient() {

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				
				load(url, webView);
				
				return super.shouldOverrideUrlLoading(view, url);
			}
			
			@Override
			public void onPageFinished(WebView view, String url) {
				
				super.onPageFinished(view, url);
				
				if (url.equals("http://api.t.sina.com.cn/oauth/authorize")) {
					
					view.loadUrl("javascript:window.JSMethod.getHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
				}
				
				
			}
		});

		webView.setWebChromeClient(new WebChromeClient() {

			@Override
			public void onProgressChanged(WebView view, int newProgress) {
				if (newProgress == 100) {
					handler.sendEmptyMessage(CLOSE_DLG);
				}
			}

		});
	}

	
	/**
	 * 
	 * @param url
	 * @param wv
	 */
	public void load(final String url, final WebView wv) {

		if (url == null || "".equals(url)) {
			return;
		}

		new Thread() {
			@Override
			public void run() {
				wv.loadUrl(url);
			}
		}.start();
	}

	
	
	
	/**
	 * 创建进度条
	 */
	@Override
	protected Dialog onCreateDialog(int id) {
		
		if (id == LOADING_DLG) {
			if (proDialog == null) {

				proDialog = new ProgressDialog(this);
				proDialog.setMessage(getString(R.string.load_auth));
				proDialog.show();
			}
		}

		return proDialog;
	}
	
	
	/**
	 * javaScript解析接口
	 * @author krui
	 *
	 */
	class JavaScriptInterface {
		
		public void getHTML(String html) {

			PIN = getPin(html);
			
			if (PIN != "") {
				Log.e("pin", PIN);
				Intent mIntent = new Intent();
				mIntent.putExtra("pin", PIN);
				setResult(RESULT_OK, mIntent);
				//一定要finish才会回跳到调用的activity
				WebViewActivity.this.finish();
			} else {
				Log.e("pin", "pin is null");
			}
			
			finish();
		}
	}

	/**
	 * 正则获取pin
	 * @param html
	 * @return
	 */
	public String getPin(String html) {
		String ret = "";
		String regEx = "[0-9]{6}";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(html);
		boolean result = m.find();
		if (result) {
			ret = m.group(0);
		}
		return ret;
	}
	
	
	
}
